<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <el-tab-pane label="角色管理">
            <el-row>
              <el-button type="primary" @click="showDialog=true">+新增角色</el-button>
            </el-row>
            <!-- 表格 -->
            <el-table
              border
              :data="list"
              style="width: 100%;margin-top:30px"
            >
              <el-table-column
                label="序号"
                width="130"
                type="index"
              />
              <el-table-column
                prop="name"
                label="角色名称"
                width="230"
              />
              <el-table-column
                prop="description"
                label="描述"
              />
              <el-table-column
                label="操作"
              >
                <template #default="{row}">
                  <!-- {{ scope.row.id }} -->
                  <el-button size="small" type="success" @click="assignPerm(row.id)">分配权限</el-button>
                  <el-button size="small" type="primary" @click="editRole(row.id)">编辑</el-button>
                  <el-button size="small" type="danger" @click="delManager(row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页 -->
            <el-row type="flex" justify="center" align="middle" style="height:60px">
              <el-pagination
                layout="prev, pager, next"
                :total="page.total"
                :page-size="page.pagesize"
                @current-change="currentChange"
              />
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="公司信息">
            <el-alert
              title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
              type="info"
              show-icon
              :closable="false"
            />
            <el-form :model="fromData" label-width="120px" style="margin-top:50px">
              <el-form-item label="公司名称">
                <el-input v-model="fromData.name" style="width:400px" disabled />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input v-model="fromData.companyAddress" style="width:400px" disabled />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="fromData.mailbox" style="width:400px" disabled />
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="fromData.remarks" type="textarea" :rows="3" disabled style="width:400px" />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>
      <!-- 弹出层 -->
      <el-dialog :title="roleForm.id?'编辑角色':'新增角色'" :visible="showDialog" @close="btnCancel">
        <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="120px">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="roleForm.name" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="roleForm.description" />
          </el-form-item>
        </el-form>
        <!-- 底部 -->
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button size="small" @click="btnCancel">取消</el-button>
            <el-button size="small" type="primary" @click="btnOK">确定</el-button>
          </el-col>
        </el-row>
      </el-dialog>

      <!-- 分配权限 -->
      <el-dialog title="分配权限" :visible="showPermDialog" @close="btnPermCancel">
        <el-tree
          ref="permTree"
          :data="permissionList"
          :props="{label:'name'}"
          :default-expand-all="true"
          :show-checkbox="true"
          :check-strictly="true"
          node-key="id"
        />
        <!-- 确定 取消 -->
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button type="primary" size="small" @click="btnPermOK">确定</el-button>
            <el-button size="small" @click="btnPermCancel">取消</el-button>
          </el-col>
        </el-row>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getCompanyDetail, getRoleList, delRole, getRoleDetail, editRoleDetail, addRole, assignPerm } from '@/api/setting'
import { getPermissionList } from '@/api/permission'
import { listToTreeData } from '@/utils'
export default {
  data() {
    return {
      showPermDialog: false,
      permissionList: [],
      roleId: '',
      showDialog: false,
      fromData: { },
      page: {
        page: 1,
        pagesize: 2,
        total: 0
      },
      list: [],
      roleForm: {
        name: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' },
          { max: 10, message: '名称最多不能超过10字符', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '角色描述不能为空', trigger: 'blur' },
          { max: 50, message: '描述文字最多不能超过50字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getCompanyDetail()
    this.getRoleList()
  },
  methods: {
    async getCompanyDetail() {
      this.fromData = await getCompanyDetail(this.$store.state.user.userInfo.companyId)
      // console.log(this.fromData)
    },
    async getRoleList() {
      const res = await getRoleList(this.page)
      console.log(res)
      this.list = res.rows
      this.page.total = res.total
    },
    currentChange(newPage) {
      this.page.page = newPage
      this.getRoleList()
    },
    async delManager(id) {
      try {
      //  1.二次确认
        await this.$confirm('是否删除该角色?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        //  2.发起请求
        await delRole(id)
        //  3.提示成功
        this.$message.success('删除成功')
        //  4.刷新数据
        this.getRoleList()
      } catch (error) {
        console.log(error)
      }
    },
    async editRole(id) {
      this.showDialog = true
      const res = await getRoleDetail(id)
      // console.log(res)
      this.roleForm = res
    },
    btnCancel() {
      // 重置表单
      this.roleForm = {
        name: '',
        description: ''
      }
      // 重置报错
      this.$refs.roleForm.resetFields()
      this.showDialog = false
    },
    async btnOK() {
      try {
        // 校验表单
        await this.$refs.roleForm.validate()
        if (this.roleForm.id) {
        // 编辑 发送请求
          await editRoleDetail(this.roleForm)
        } else {
        // 新增
          await addRole(this.roleForm)
        }
        // 提示成功
        this.$message.success('操作成功')
        // 关闭弹窗
        this.showDialog = false
        // 更新数据
        this.getRoleList()
      } catch (error) {
        console.log(error)
      }
    },
    // 分配权限
    async assignPerm(id) {
      // 获取所有权限
      const res = await getPermissionList()
      const permActive = res.filter(item => item.enVisible === '1')
      this.permissionList = listToTreeData(permActive, '0')
      console.log(this.permissionList)
      // 获取角色详情里的权限id
      const { permIds } = await getRoleDetail(id)
      console.log(permIds)
      this.showPermDialog = true
      this.$nextTick(() => {
        this.$refs.permTree.setCheckedKeys(permIds)
      })
      this.roleId = id
    },
    btnPermCancel() {
      this.$refs.permTree.setCheckedKeys([])
      this.showPermDialog = false
    },
    async btnPermOK() {
      await assignPerm({
        id: this.roleId,
        permIds: this.$refs.permTree.getCheckedKeys()
      })
      this.$message.success('修改成功')
      this.showPermDialog = false
    }
  }
}
</script>

<style lang="scss" scoped>
.dashboard {
  &-container {
    margin: 30px;
  }
  &-text {
    font-size: 30px;
    line-height: 46px;
  }
}
</style>
